/**
 *
 * @param url 绝对路径
 */
export default async function request<T = any>({
  url,
  method,
  header,
  data,
}: any): Promise<T | string | Blob | boolean> {
  const options: any = {
    method: method ?? "GET",
    headers: {},
    mode: "cors",
    credentials: "same-origin",
  };

  // 判断header
  if (header) {
    options.headers = header;
  } else {
    if (data instanceof FormData) {
      // 传FormData对象不能设Content-Type
      options.body = data;
    } else {
      // 传JSON字符串
      options.headers = {
        "Content-Type": "application/json",
        // 'Content-Type': 'application/x-www-form-urlencoded',
      };
      options.body = JSON.stringify(data);
    }
  }

  const response = await fetch(url, options);

  const contentType = response.headers.get("Content-Type");
  let responseBody: T | string | Blob;

  if (contentType?.includes("application/json")) responseBody = await response.json();
  else if (contentType?.includes("text/html")) responseBody = await response.text();
  else responseBody = await response.blob()

  return responseBody;
}
